import 'dart:async';

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:guochaoapp/common/utils/http_client.dart';
import 'package:guochaoapp/common/constant/api.dart';
import 'package:guochaoapp/common/utils/reg_utils.dart';
import 'package:guochaoapp/model/user_entity.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:guochaoapp/routes/app_pages.dart';
import 'package:guochaoapp/services/user_service.dart';

class GCEditPasswordController extends GetxController {
  UserService userService = Get.find();

  final GlobalKey registerFormKey = GlobalKey<FormState>();
  final phone = "".obs;
  final randomCode = "".obs;
  final password = "".obs;
  final account = "".obs;
  final securePassword = true.obs;

  final tapGestureRecognizer = TapGestureRecognizer();

  Timer timer;
  final countDownTime = 0.obs;

  getRandomCode() {
    if (!RegUtils.isChinaPhoneLegal(this.phone.value)) {
      EasyLoading.showError("请输入正确的手机号");
      return;
    }

    if (countDownTime.value > 0) {
      return;
    }

    countDownTime.value = 60;

    const oneSec = const Duration(seconds: 1);

    var callback = (timer) => {
      countDownTime < 1
          ? timer.cancel()
          : countDownTime.value = countDownTime.value - 1
    };

    timer = Timer.periodic(oneSec, callback);

    HttpClient.request(
        url: SmsApi.randomCode + "/$phone",
        method: Method.PUT,
        onSuccess: (r,_) {
          EasyLoading.showSuccess("发送成功");
        },
        onFailed: (error) {
          EasyLoading.showError(error);
        });
  }

  submitButtonAction() {
    if ((registerFormKey.currentState as FormState).validate()) {
      var data = {
        "phone": phone,
        "randomCode": randomCode,
        "oriPassword": password,
      };
      HttpClient.request(
          url: UserApi.resetPsw,
          method: Method.POST,
          data: data,
          onSuccess: (r,_) {
            EasyLoading.showSuccess("修改密码成功");
          },
          onFailed: (error) {
            EasyLoading.showError(error);
          });
    }
  }

  @override
  void onClose() {
    tapGestureRecognizer.dispose();
  }
}